﻿using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KLS.PPDS.Utilities.BaseController;
using KLS.PPDS.Web.Models;
using KLS.PPDS.Core.Entity;
using KLS.PPDS.ApplicationService.Manager;
using KLS.PPDS.Utilities.Attributes;
using System.IO;
using KLS.PPDS.Utilities;
using KLS.PPDS.Utility;
namespace KLS.PPDS.Web.Controllers.Article
{
    public class ArticleContentController : BaseController
    {
        //
        // GET: /ArticleContent/
        [AjaxAuthorize(Roles = RoleConstant.All)]
        public ActionResult Index(int articleId, int publicationId)
        {
            ModelState.Clear();
           // var directory = @"~/App_Data/uploads";
            ArticleContent content = new ArticleContent();
            content.ArticleId = articleId;
            
            ArticleContentManager.Save(content);

            ArticleContentViewModel model = new ArticleContentViewModel();

            content.CopyPropertyValue<ArticleContent, ArticleContentViewModel>(model);

            model = ArticleContentModel.GetViewModel(model.Id, publicationId);


            return View("~/Views/Article/ArticleContent.ascx", model);
        }


        /// <summary>
        /// UploadImage
        /// </summary>
        /// <param name="file"></param>
        /// <param name="comId"></param>
        /// <param name="pubId"></param>
        /// <param name="artId"></param>
        /// <param name="contentId"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public string UploadImage(HttpPostedFileBase file, int comId, int pubId, int artId, int contentId, string type)
        {
            if (ArticleContentModel.ValidateUploadFile(contentId, type))
            {
                var imagePath = ArticleContentModel.GetArtileContentImageFolder(comId, pubId, artId, contentId);
                var thumbFilePath = ArticleContentModel.GetArtileContentImageThumbnailFolder(comId, pubId, artId, contentId);                

                ArticleContentModel.SaveFiles(file, imagePath, thumbFilePath, string.Empty, type, 0, contentId);
            }            
            return contentId.ToString();
        }


        /// <summary>
        /// UploadText
        /// </summary>
        /// <param name="file"></param>
        /// <param name="comId"></param>
        /// <param name="pubId"></param>
        /// <param name="artId"></param>
        /// <param name="contentId"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public string UploadText(HttpPostedFileBase file, int comId, int pubId, int artId, int contentId, string type)
        {
            if (ArticleContentModel.ValidateUploadFile(contentId, type))
            {
                var textPath = ArticleContentModel.GetArtileContentTextFolder(comId, pubId, artId, contentId);
                ArticleContentModel.SaveFiles(file, string.Empty, string.Empty, textPath, type, artId, contentId);
            }
            return contentId.ToString();
        }

        [AjaxAuthorize(Roles = RoleConstant.All)]
        public ActionResult LoadImageContent(int contentId)
        {

            var con = ArticleContentManager.GetArticleContentById(contentId);

            var atr = ArticleManager.GetArticleById(con.ArticleId);

            var pub = PublicationManager.GetPublicationById(atr.PublicationId);

            var model = ArticleContentModel.GetViewModel(contentId, pub.Id);

            return View("~/Views/Article/NewImageThumbnail.ascx", model);
        }

        [AjaxAuthorize(Roles = RoleConstant.All)]
        public ActionResult LoadTextContent(int contentId)
        {

            //var con = ArticleContentManager.GetArticleContentById(contentId);

            //var atr = ArticleManager.GetArticleById(con.ArticleId);

            //var pub = PublicationManager.GetPublicationById(atr.PublicationId);

            var model = ArticleContentModel.GetViewModel(contentId);

            return View("~/Views/Article/ArticleContent.ascx", model);
        }


        [AjaxAuthorize(Roles = RoleConstant.All)]
        public ActionResult GetContentByID(int contentId)
        {
           
            var model = ArticleContentModel.GetViewModel(contentId);

            return View("~/Views/Article/TextThumbnail.ascx", model);
        }


        [AjaxAuthorize(Roles = RoleConstant.All)]
        public ActionResult Delete(int publicationId,int articleId,int id) 
        {
            ModelState.Clear();
            ArticleContentModel.Delete(publicationId,articleId,id);
            return null;
        }

        /// <summary>
        /// DeleteImage
        /// </summary>
        /// <param name="pubId"></param>
        /// <param name="artId"></param>
        /// <param name="conId"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        [AjaxAuthorize(Roles = RoleConstant.All)]
        public ActionResult DeleteImage(int pubId, int artId, int conId, string file) 
        {
            ModelState.Clear();
            var pub = PublicationManager.GetPublicationById(pubId);
            var path = Path.Combine(ArticleContentModel.GetArtileContentImageFolder(pub.CompanyId,pubId, artId, conId), file);
            var thumbsPath = Path.Combine(ArticleContentModel.GetArtileContentImageThumbnailFolder(pub.CompanyId, pubId, artId, conId), FileUtil.ImageGetThumbnailsFileName(file));
            ArticleContentModel.DeleteImageFile(path);
            ArticleContentModel.DeleteImageFile(thumbsPath);

            ArticleContentModel.DeleteFileDb(conId, Path.GetFileName(path));

            var model = ArticleContentModel.GetViewModel(conId, pubId);
            //return View("~/Views/Article/ArticleContent.ascx", model);
            return View("~/Views/Article/NewImageThumbnail.ascx", model);
           
        }

         [AjaxAuthorize(Roles = RoleConstant.All)]
        public ActionResult DeleteTextFile(int pubId, int artId, int conId)
        {
            var pub = PublicationManager.GetPublicationById(pubId);
            var path = ArticleContentModel.GetArtileContentTextFolder(pub.CompanyId, pubId, artId, conId);
            ArticleContentModel.DeleteTextFolder(path);  
            var model = ArticleContentModel.GetViewModel(conId, pubId);
         //   return View("~/Views/Article/ArticleContent.ascx", model);
            return View("~/Views/Article/ArticleContent.ascx", model);
        }

         [AjaxAuthorize(Roles = RoleConstant.All)]
         public ActionResult DownloadTextFile(int pubId, int artId, int conId, string file)
         {
             var pub = PublicationManager.GetPublicationById(pubId);
             var path = ArticleContentModel.GetArtileContentTextFolder(pub.CompanyId, pubId, artId, conId);

             path = Path.Combine(path, file);

             var art = ArticleManager.GetArticleById(artId);
             var cont = ArticleContentManager.GetArticleContentById(conId);
             if (art.IsReadyForGraphic)
             {
                 // path = path.Replace(WebConfig.BaseFolder, WebConfig.PublicationPackageFolder);
                 path = ArticleContentModel.GetPackageArtileContentTextFolder(conId);
                 path = Path.Combine(path, file);
             }
             
             if (System.IO.File.Exists(path))
             {
                 return new GenericFileActionResult() { FullFileName = path };
             }

             return null;
         }


         [AjaxAuthorize(Roles = RoleConstant.All)]
        public ActionResult ViewImage(int pubId, int artId, int conId, string file) 
        {
            var pub = PublicationManager.GetPublicationById(pubId);
            var path = Path.Combine(ArticleContentModel.GetArtileContentImageFolder(pub.CompanyId, pubId, artId, conId), file);

            var art = ArticleManager.GetArticleById(artId);
            var cont = ArticleContentManager.GetArticleContentById(conId);
            if (art.IsReadyForGraphic)
            {
               // path = path.Replace(WebConfig.BaseFolder, WebConfig.PublicationPackageFolder);
                path = ArticleContentModel.GetPackageArtileContentImageFolder(conId);
                path =Path.Combine(path, file);
            }


            if (System.IO.File.Exists(path))
            {
                return new GenericFileActionResult() { FullFileName = path };
            }

            return null;

        }

         [AjaxAuthorize(Roles = RoleConstant.All)]
        public FileResult ShowOriginalImage(int pubId, int artId, int conId, string file)
        {
            var pub = PublicationManager.GetPublicationById(pubId);
            var path = Path.Combine(ArticleContentModel.GetArtileContentImageFolder(pub.CompanyId, pubId, artId, conId), file);
            // path = Server.MapPath("~/Content/images/thumbnail.png");

            //using (FileStream stream = new FileStream(file, FileMode.OpenOrCreate))
            var art = ArticleManager.GetArticleById(artId);
            var cont = ArticleContentManager.GetArticleContentById(conId);
            if (art.IsReadyForGraphic)
            {
                path = path.Replace(WebConfig.BaseFolder, WebConfig.PublicationPackageFolder);
            }

            if (System.IO.File.Exists(path))
            {
                var stream = new FileStream(path, FileMode.Open);

                FileStreamResult result = new FileStreamResult(stream, "image/png");
                result.FileDownloadName = file;

                return result;
            }
            else
            {
                path = Server.MapPath("~/Content/images/thumbnail.png");

                var stream = new FileStream(path, FileMode.OpenOrCreate);

                FileStreamResult result = new FileStreamResult(stream, "image/png");
                result.FileDownloadName = "dl.png";

                return result;
            }



            //return null;

        }

         [AjaxAuthorize(Roles = RoleConstant.All)]
        public FileResult ShowThumbnailImage(int pubId, int artId, int conId, string file)
        {
            var pub = PublicationManager.GetPublicationById(pubId);
            var path = Path.Combine(ArticleContentModel.GetArtileContentImageThumbnailFolder(pub.CompanyId,pubId, artId, conId), FileUtil.ImageGetThumbnailsFileName(file));
            var art = ArticleManager.GetArticleById(artId);
            
            var cont = ArticleContentManager.GetArticleContentById(conId);
            if (art.IsReadyForGraphic) 
            {
                //path = path.Replace(WebConfig.BaseFolder, WebConfig.PublicationPackageFolder);
                path = ArticleContentModel.GetPackageArtileContentImageThumbnailFolder(conId);
                
                path = Path.Combine(path, file);
            }

           // path = Server.MapPath("~/Content/images/thumbnail.png");

            //using (FileStream stream = new FileStream(file, FileMode.OpenOrCreate))

            if (System.IO.File.Exists(path))
            {
                var stream = new FileStream(path, FileMode.OpenOrCreate);

                FileStreamResult result = new FileStreamResult(stream, "image/png");
                result.FileDownloadName = "dl.png";

                return result;
            }
            else
            {
                path = Server.MapPath("~/Content/images/thumbnail.png");

                var stream = new FileStream(path, FileMode.OpenOrCreate);

                FileStreamResult result = new FileStreamResult(stream, "image/png");
                result.FileDownloadName = "dl.png";

                return result;
            }

            
            
            //return null;

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [AjaxAuthorize(Roles = RoleConstant.All)]
        public ActionResult SaveArticleContent(ArticleContentViewModel model) 
        {                       
            ModelState.Clear();
           
            var result = string.Empty;
            var imageError = string.Empty;
            var textError = string.Empty; 

            //processing file
            var index = 0;
            foreach (var file in Request.Files)
            {
                var hpf = Request.Files[index] as HttpPostedFileBase;
                
                if (hpf.ContentLength > 0)
                {
                    if (model.Id > 0) 
                    {
                        result = ArticleContentModel.SaveFiles(hpf, model.ImageFilePath, model.ThumbsFilePath, model.TextFilePath, file.ToString(),model.ArticleId,model.Id); 
                    }                    
                    if (!String.IsNullOrEmpty(result)) 
                    {
                        //if (imageError.Contains(""))

                        if (file.ToString().Contains("txt")) 
                        {
                            textError = result;
                        }
                        else if (file.ToString().Contains("img")) 
                        {
                            imageError +=   result + "<br/>";
                        }
                    }
                }
                index++;
            }
          
            //return JsonMessage("test");
        
            var chk = Request.Form.AllKeys.Where(c => c.StartsWith("chk")).ToList();
            ArticleContentModel.NewProcessImageFiles(chk, model.ImageFilePath, model.ArticleId, model.Id);
            //model.Article = ArticleManager.GetArticleById(model.ArticleId);

            if (model.OldTextDisable.Equals(true) && String.IsNullOrEmpty(model.Headline) && CommonSession.IsUserJournalist) 
            {
                model.Headline = model.OldHeadline;
                model.Comments = model.OldComments;
                model.IsReadyForEditor = model.OldReadyForEditing;
                model.IsReadyForGraphic = model.OldReadyForGraphics;
            }

            ArticleContentModel.SaveArticleContent(model);
            ArticleContentModel.SaveCommnetsText(model.Comments, model.PublicationId, model.ArticleId, model.Id);

            model = ArticleContentModel.GetViewModel(model.Id, model.PublicationId);


            model.TextFileError = textError;
            model.ImageFileError = imageError;
            return View("~/Views/Article/ArticleContent.ascx", model);
        }
    }
}
